package com.woniu.controller;

import com.woniu.Service.MenuService;
import com.woniu.Service.RoleMenuService;
import com.woniu.entity.RoleMenu;
import com.woniu.util.JsonResult;
import com.woniu.util.JwtUtil;
import com.woniu.vo.MenuVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @Author: Gwj
 * @Date: 2024/7/1 19:32
 */
@RestController
@RequestMapping("/menu")
@Slf4j
@Api(value = "菜单接口", tags = "所有菜单功能")
public class MenuController {
    @Resource
    private MenuService menuService;

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private RoleMenuService roleMenuService;

    /**
     * 获取菜单 根据用户名获取用户拥有的权限菜单
     *
     * @param accountName
     * @return
     * @throws Exception
     */
    @GetMapping("/getMenuName")
    @ApiOperation(value = "获取菜单名字")
    public JsonResult<List<MenuVo>> getMenuName(String accountName) throws Exception {
        log.info("从前端获取的用户名：" + accountName);
        List<MenuVo> list = menuService.selectMenuByAccountName(accountName);
        return JsonResult.ok(200, list);
    }

    /**
     * 获取所有权限
     *
     * @return
     * @throws Exception
     */
    @GetMapping("/getAllPermission")
    @ApiOperation(value = "获取所有权限")
    public JsonResult<List<MenuVo>> getAllPermission() throws Exception {
        List<MenuVo> menuList = menuService.selectAllPermission();
        return JsonResult.ok(200, menuList);
    }

    /**
     * 获取角色所有权限
     *
     * @return
     * @throws Exception
     */
    @GetMapping("/getPermissionById/{roleId}")
    @ApiOperation(value = "获取角色拥有权限")
    public JsonResult<Set<Integer>> getPermissionById(@PathVariable Integer roleId) throws Exception {
        Set<Integer> set = menuService.getPermissionById(roleId);
        return JsonResult.ok(200, set);
    }

    @PutMapping("/grantPermissionByRoleId")
    @ApiOperation(value = "角色授权")
    private JsonResult grantPermissionByRoleId(int roleId, int[] ids) throws Exception {
        ArrayList<RoleMenu> list = new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            list.add(new RoleMenu(roleId, ids[i]));
        }
        int i = roleMenuService.addRoleMenu(roleId, list);
        return JsonResult.ok(200, i);
    }
}
